import pandas as pd
def get_market_share_data_optimized(df, year=2023):
    """
    获取市场份额数据（优化版）
    参数: df - 预加载的销售数据DataFrame
    """
    try:
        # 筛选指定年份的数据
        year_data = df[df['年份'] == year]
        
        if year_data.empty:
            return {
                'success': False,
                'error': f'没有找到{year}年的数据'
            }
        
        # 按厂商分组计算年度总销量
        manufacturer_sales = year_data.groupby('厂商')['销量'].sum().reset_index()
        
        # 计算总销量
        total_sales = manufacturer_sales['销量'].sum()
        
        # 计算市场份额
        manufacturer_sales['份额'] = (manufacturer_sales['销量'] / total_sales * 100).round(2)
        
        # 按销量降序排序，取前8名，其余归入"其他"
        top_manufacturers = manufacturer_sales.sort_values('销量', ascending=False).head(8)
        
        manufacturers = top_manufacturers['厂商'].tolist()
        shares = top_manufacturers['份额'].tolist()
        
        # 如果有超过8个厂商，将剩余的归入"其他"
        if len(manufacturer_sales) > 8:
            other_share = manufacturer_sales.iloc[8:]['份额'].sum()
            if other_share > 0:
                manufacturers.append('其他')
                shares.append(round(other_share, 2))
        
        return {
            'success': True,
            'year': year,
            'manufacturers': manufacturers,
            'shares': shares
        }
        
    except Exception as e:
        return {
            'success': False,
            'error': f'获取市场份额数据失败: {str(e)}'
        }
